/*
 * PhotonRTOS础光实时操作系统 -- 调用场景分析实现文件
 *
 * Copyright (C) 2022, 2023 国科础石(重庆)软件有限公司
 *
 * 作者: Rui Yang <yangrui@kernelsoft.com>
 *
 * License terms: GNU General Public License (GPL) version 3
 *
 */

#include <autosar/internal.h>
#include <photon/cpu.h>
#include <photon/sched.h>

static VAR(ApplicationType, AUTOMATIC) os_current_run_context[MAX_CPUS];

//設置新的上下文，返回之前的上下文
FUNC(ApplicationType, OS_CODE)
refresh_os_run_context(
    VAR(ApplicationType, AUTOMATIC) context)
{
    VAR(ApplicationType, AUTOMATIC) last_context;
    VAR(CoreIdType, AUTOMATIC) cpu_id = autosar_get_core_id();
    VAR(int32_t, AUTOMATIC) count = 0;
    VAR(int32_t, AUTOMATIC) location = 0;

	if(context > ENV_OS_RUN_CONTEXT_MAX || context < 0)
	{
		dump_stack();
	}
	for(count = 0, location = 0; \
		location < sizeof(os_run_context) * 8; \
		location++)
	{
		if((context >> location) & 0x01)
		{
			count++;
		}
		if(count > 1){
			dump_stack();
		}
	}

	last_context = os_current_run_context[cpu_id];
	os_current_run_context[cpu_id] = context;

	return last_context;
}

//恢復之前的上下文
FUNC(void, OS_CODE)
restore_os_run_context(
    VAR(ApplicationType, AUTOMATIC) context)
{
	VAR(CoreIdType, AUTOMATIC) cpu_id = autosar_get_core_id();
	os_current_run_context[cpu_id] = context;
}

FUNC(StatusType, OS_CODE)
os_run_context_seted(
    VAR(ApplicationType, AUTOMATIC) context)
{
	VAR(CoreIdType, AUTOMATIC) cpu_id = autosar_get_core_id();
	if(os_current_run_context[cpu_id] & context){
        return E_OK;
    }
    return E_OS_CALLEVEL;
}

FUNC(void, OS_CODE)
os_run_context_init(void){
	VAR(CoreIdType, AUTOMATIC) cpu_id = autosar_get_core_id();
	os_current_run_context[cpu_id] = ENV_TASK;
}